const Service = require('egg').Service;

class FeedbackService extends Service {
  /**
   * 创建反馈
   * @param {Object} params 反馈参数
   */
  async create(params) {
    const { ctx } = this;
    //更新到数据库
    try {
        await ctx.app.mysql.insert('feedback', params);
        return true;
    } catch (error) {
        ctx.logger.error('创建反馈失败:', error);
        return false;
    }
  }
  
  /**
   * 获取反馈列表
   * @param {Object} params 查询参数
   */
  async list(params) {
    const { ctx } = this;
    const { page, pageSize } = params;
    const offset = (page - 1) * pageSize;
    
    // 查询数据
    const sql = `
      SELECT id, content, contact, user_agent, ip, created_at 
      FROM feedback 
      ORDER BY id DESC 
      LIMIT ?, ?
    `;
    
    // 查询总数
    const countSql = 'SELECT COUNT(*) as count FROM feedback';
    
    try {
      const [rows, countResult] = await Promise.all([
        ctx.db.query(sql, [offset, pageSize]),
        ctx.db.query(countSql)
      ]);
      
      return {
        list: rows,
        pagination: {
          page,
          pageSize,
          total: countResult[0].count
        }
      };
    } catch (error) {
      ctx.logger.error('获取反馈列表失败:', error);
      return {
        list: [],
        pagination: {
          page,
          pageSize,
          total: 0
        }
      };
    }
  }
}

module.exports = FeedbackService;